<?php


namespace app\common\model;


use helper\Arr;

class Permission extends Base
{
    /**
     * 相对的关联
     * @return \think\model\relation\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_permission');
    }

    /**
     * 获取层级的数据
     * @param $data array 用户有的权限
     * @return array
     */
    public static function treeData(array $data = []): array
    {
        // 获取权限
        $list = self::field('id,parent_id, title')->select()->toArray();
        foreach ($list as $key => $val) {
            $list[$key]['field']   = 'permission_ids[]';
            $list[$key]['checked'] = isset($data) && in_array($val['id'], $data);
            $list[$key]['spread']  = false;//$val['parent_id']==0
        }
        return Arr::subTree($list);
    }

    /**
     * 菜单
     * @param bool $is_menu
     * @return array
     */
    public static function getMenu(bool $is_menu = true)
    {
        $where = [];
        if ($is_menu) {
            $where[] = ['status', '=' ,1];
        }
        $list = self::field('id,parent_id,name,title,icon,route')
            ->order('sort asc, id asc')
            ->where($where)
            ->select()
            ->toArray();
        return $is_menu ? Arr::subTree($list, 0, 'list') : Arr::tree($list);
    }

    /**
     * 权限分配角色
     * @param $role
     */
    public function assignRole($role)
    {
        
    }

    /**
     * 权限更新
     * @param $roles
     */
    public function syncRoles($roles)
    {
        
    }

    /**
     * 移除权限
     * @param $role
     */
    public function removeRole($role)
    {
        
    }
}